﻿// Copyright © Microsoft Corporation.  All Rights Reserved.
// This code released under the terms of the 
// Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)

using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;

namespace TheOliver.Phone.Tools.Controls
{
    public partial class NumberPickerControl : UserControl, INotifyPropertyChanged
    {
        public NumberPickerControl()
        {
            InitializeComponent();

            this.Loaded += (s, e) =>
                {
                    _parentPage = Helper.GetParentPage(this);
                };
        }

        PhoneApplicationPage _parentPage;
        public bool ShowDecimal { get; set; }

        private string _numberTitle = "Number Value";
        public string NumberTitle
        {
            get { return _numberTitle; }
            set { _numberTitle = value; }
        }

        private void _number_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            NavigationService ns = Helper.GetNavigationService(this);
            if (ns != null)
            {
                double number = (double)this.DataContext;
                string uri = "/TheOliver.Phone.Tools;component/Controls/NumberPickerPage.xaml?v=" + number + "&d=" + ShowDecimal.ToString();

                PhoneApplicationFrame frame = Application.Current.RootVisual as PhoneApplicationFrame;
                
                frame.Navigate(new Uri(uri, UriKind.Relative));
                _parentPage.NavigationService.Navigated += NavigationService_Navigated;
            }
        }

        NumberPickerPage _numberPickerPage;
        void NavigationService_Navigated(object sender, NavigationEventArgs e)
        {
            if (e.NavigationMode == NavigationMode.New)
            {
                _numberPickerPage = (NumberPickerPage)e.Content;
                ////_numberPickerPage.NumberValue = (double)this.DataContext;
            }
            else if (e.NavigationMode == NavigationMode.Back)
            {
                this.DataContext = _numberPickerPage.NumberValue;
                _parentPage.NavigationService.Navigated -= NavigationService_Navigated;
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;
        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
